<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="客户" prop="kehu_id">
                    <el-select v-model="formData.kehu_id" filterable remote reserve-keyword placeholder="输入关键词搜索"
                        remote-show-suffix :remote-method="remoteMethod" :loading="loading" @change="getaddress">
                        <el-option v-for="item in kehu" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="收货地址" prop="address_id">

                    <el-select v-model="formData.address_id" clearable placeholder="请选择">
                        <el-option v-for="item in addressslist" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="制单" prop="create">
                    <el-input readonly v-model="formData.create" />
                </el-form-item>
                <el-form-item label="客户订单号" prop="orderNo">
                    <el-input v-model="formData.orderNo" clearable placeholder="请输入客户订单号" />
                </el-form-item>
                <el-form-item label="下单时间" prop="create_time">
                    <el-date-picker class="flex-1 !flex" v-model="formData.create_time" clearable type="date"
                        value-format="YYYY-MM-DD" placeholder="选择下单时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="交货时间" prop="de_time">
                    <el-date-picker class="flex-1 !flex" v-model="formData.de_time" clearable type="date"
                        value-format="YYYY-MM-DD" placeholder="选择交货时间">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                </el-form-item>

            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="ordersEdit">
import type { FormInstance } from "element-plus";
import { apiKehuLists } from '@/api/kehu/kehu'
import { apiKehuAddressLists } from '@/api/kehu/address'
import Popup from "@/components/popup/index.vue";
import {
    apiOrdersAdd,
    apiOrdersEdit,
    apiOrdersDetail,
} from "@/api/orders/orders";
import { timeFormat } from "@/utils/util";
import type { PropType } from "vue";
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({}),
    },
});
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == "edit" ? "编辑销售订单" : "新增销售订单";
});

// 表单数据
const formData = reactive({
    id: "",
    kehu_id: "",
    create: userStore.userInfo.name,
    orderNo: "",
    create_time: timeFormat(new Date().getTime(),'yyyy-mm-dd hh:MM:ss'),
    de_time: "",
    remark: "",
    address_id: "",
});

// 表单验证
const formRules = reactive<any>({});
const list = ref<any>([])
let kehu = ref<any>([])
const loading = ref(false)
let addressslist = ref<AddressItem[]>([])
onMounted(() => {
    apiKehuLists({ page_size: 999, page_no: 1 }).then(res => {
        list.value = res.lists
    })

})
const getaddress = async (id: number) => {
    addressslist.value = []
    formData.address_id = ''
    await apiKehuAddressLists({
        kehu_id: id
    }).then(res => {

        addressslist.value = res.lists
    })

}
const remoteMethod = (query: string) => {
    if (query) {
        loading.value = true
        setTimeout(() => {
            loading.value = false
            kehu.value = list.value.filter((item: { name: string; }) => {
                return item.name.toLowerCase().includes(query.toLowerCase())
            })
        }, 200)
    } else {
        kehu.value = []
    }
}
// 获取详情
const setFormData = async (row: Record<any, any>) => {
    const data = await apiOrdersDetail({ id: row.id });
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key];
        }
    }
};

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate();
    const data = { ...formData };
    mode.value == "edit" ? await apiOrdersEdit(data) : await apiOrdersAdd(data);
    popupRef.value?.close();
    emit("success");
};

//打开弹窗
const open = (type = "add") => {
    mode.value = type;
    popupRef.value?.open();
};

// 关闭回调
const handleClose = () => {
    emit("close");
};

defineExpose({
    open,
    setFormData,
});
</script>
